package com.ruibang.glass.equipment.service.impl.device;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.equipment.constant.EquipmentErrorCode;
import com.ruibang.glass.equipment.domain.req.device.DeviceAllPageReq;
import com.ruibang.glass.equipment.dto.SelectNewDTO;
import com.ruibang.glass.equipment.entity.device.SparePartsInventory;
import com.ruibang.glass.equipment.mapper.device.SparePartsInventoryMapper;
import com.ruibang.glass.equipment.service.SparePartsInventoryService;
import com.ruibang.glass.equipment.service.WareHouseManagementService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 备件台账服务类
 * </p>
 *
 * @author mameng
 * @since 2024-03-20
 */
@Slf4j
@Service
public class SparePartsInventoryServiceImpl extends ServiceImpl<SparePartsInventoryMapper, SparePartsInventory> implements SparePartsInventoryService {

    /**
     * 备件台账列表
     * @param deviceAllPageReq
     * @return
     */
    @Override
    public IPage<SparePartsInventory> queryPage(DeviceAllPageReq deviceAllPageReq) {
        return baseMapper.queryPage(new Page<>(deviceAllPageReq.getPageNo(), deviceAllPageReq.getPageSize()), deviceAllPageReq);
    }

    /**
     * 新增修改
     * @param repairPlan
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody updateOrAddById(SparePartsInventory repairPlan) {
        if (!org.apache.commons.lang.StringUtils.isBlank(repairPlan.getWarehouseName())) {
            repairPlan.setWarehouseName(repairPlan.getWarehouseName());
        }
        if (StringUtils.isBlank(repairPlan.getId())) {
            Long count = baseMapper.selectCount(Wrappers.<SparePartsInventory>lambdaQuery().eq(SparePartsInventory::getSparePartsNumber, repairPlan.getSparePartsNumber()));
            if (count>0){
                return ResultBody.fail(EquipmentErrorCode.SPARE_PARTS_NUMBER_NAME_IS_EXIST.getCode(),EquipmentErrorCode.SPARE_PARTS_NUMBER_NAME_IS_EXIST.getMsg());
            }
            baseMapper.insert(repairPlan);
            return ResultBody.success();
        }
        baseMapper.updateById(repairPlan);
        return ResultBody.success();
    }

    /**
     * 下拉框
     * @return
     */
    @Override
    public ResultBody getNameList() {
        List<SparePartsInventory> list = baseMapper.selectList(Wrappers.<SparePartsInventory>lambdaQuery()
                .select(SparePartsInventory::getSparePartsName, SparePartsInventory::getModel, SparePartsInventory::getUnit,SparePartsInventory::getSparePartsNumber, SparePartsInventory::getId));
        List<SelectNewDTO> nameList = new ArrayList<>();
        List<SelectNewDTO> unitList = new ArrayList<>();
        List<SelectNewDTO> modelList = new ArrayList<>();
        List<SelectNewDTO> spartsList = new ArrayList<>();
        for (SparePartsInventory sparePartsInventory : list) {
            SelectNewDTO selectDTO =  new SelectNewDTO();
            selectDTO.setLabel(sparePartsInventory.getSparePartsName());
            selectDTO.setValue(sparePartsInventory.getId());
            selectDTO.setNumber(String.valueOf(sparePartsInventory.getStockQuantity()));
            nameList.add(selectDTO);
            SelectNewDTO selectDTO1 = new SelectNewDTO();
            selectDTO1.setLabel(sparePartsInventory.getUnit());
            selectDTO1.setValue(sparePartsInventory.getId());
            unitList.add(selectDTO1);
            SelectNewDTO selectDTO2 = new SelectNewDTO();
            selectDTO2.setLabel(sparePartsInventory.getModel());
            selectDTO2.setValue(sparePartsInventory.getId());
            modelList.add(selectDTO2);
            SelectNewDTO selectDTO3 = new SelectNewDTO();
            selectDTO3.setLabel(sparePartsInventory.getSparePartsNumber());
            selectDTO3.setValue(sparePartsInventory.getId());
            spartsList.add(selectDTO3);
        }
        Map<String, List<SelectNewDTO>> map = new HashMap<>();
        map.put("name", nameList);
        map.put("unit", unitList);
        map.put("model", modelList);
        map.put("number", spartsList);
        return ResultBody.success(map);
    }

    /**
     * 导出
     * @param machiningReq
     * @param response
     */
    @Override
    public void export(DeviceAllPageReq machiningReq, HttpServletResponse response) {
        String fileName = "报废报表" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + ".xlsx";
        try {
            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

            // 设置响应内容类型和字符编码
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");

            // 设置Content-Disposition头部，告诉浏览器这是一个文件下载请求
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

            // 获取导出数据
            IPage<SparePartsInventory> checkList = baseMapper.queryPage(new Page<SparePartsInventory>(0L, 2000L), machiningReq);
            List<SparePartsInventory> list = checkList.getRecords();

            // 使用EasyExcel写入数据到响应输出流
            EasyExcel.write(response.getOutputStream(), SparePartsInventory.class).excelType(ExcelTypeEnum.XLSX).sheet("报废报表").doWrite(list);

            // 刷新输出流
            response.flushBuffer();
        } catch (IOException e) {
            throw new ServiceException(EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getCode()
                    ,EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getMsg());
        }
    }


}
